package com.harr.noddles.crawler;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.URISyntaxException;

public class Bet365Client {

    private HttpGet httpGet;
    private CloseableHttpClient client;
    private CloseableHttpResponse resp;

    public void close() {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        if (resp != null) {
            try {
                resp.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public String getByPD(String pd) {
        try {
            URIBuilder uri = new URIBuilder("https://www.7788365365.com/SportsBook.API/web" +
                    "?lid=10&zid=0&pd=&cid=42&ctid=42");
            uri.setParameter("pd", pd);
            httpGet = new HttpGet(uri.build());
        } catch (URISyntaxException e) {
            System.out.println("uri error: " + e.getMessage());
        }
        try {
            client = HttpClients.createDefault();
            resp = client.execute(httpGet);
            HttpEntity entity = resp.getEntity();
            InputStream ins = entity.getContent();
            StringBuilder out = new StringBuilder();
            byte[] b = new byte[4096];
            for (int n; (n = ins.read(b)) != -1; ) {
                out.append(new String(b, 0, n));
            }
            return out.toString();
        } catch (ConnectException e) {
            System.out.println("connection error: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("io error: " + e.getMessage());
        } finally {
            close();
        }
        return null;
    }

}
